package com.fenghuajueli.module_host;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.fenghuajueli.libbasecoreui.BaseApplication;
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo;
import com.fenghuajueli.libbasecoreui.constants.ConfigConstants;
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils;
import com.fenghuajueli.libbasecoreui.utils.PrivacyDialogBuilder;
import com.fenghuajueli.libbasecoreui.utils.PrivacyDialogConfig;
import com.fenghuajueli.libbasecoreui.widget.PrivacyAgreementDialog;
import com.fenghuajueli.module_host.databinding.ActivityLauncherBinding;
import com.fenghuajueli.module_route.CommonRoute;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.disposables.Disposable;

@Route(path = CommonRoute.COMMON_LAUNCHER)
public class LauncherActivity extends AppCompatActivity {

    private RxPermissions rxPermissions;
    private Disposable dispose;
    private ActivityLauncherBinding binding;

    /**
     * 上一次权限申请的时间  规范要求越来越严的情况下 不得在每次启动时就申请，需要做24小时的间隔
     */
    public static final String KEY_LAST_APPLY_PERMISSION_TIME = "permission_last_time";

    private Handler delayHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        binding = ActivityLauncherBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        rxPermissions = new RxPermissions(this);
        showDialog();
    }


    private void showDialog() {
        if (!MmkvUtils.get(ConfigConstants.MMKVKEY.privacyDialogIsShow.name(), false)) {
            PrivacyAgreementDialog privacyAgreementDialog = PrivacyDialogBuilder.create(this)
                    .setCancelName("取消")
                    .setConfirmName("同意")
                    .setDialogTitle("用户隐私协议")
                    .setReplayCompanyName(AppConfigInfo.APP_COMPANY)
                    .setReplayAppName(AppConfigInfo.APP_NAME)
                    .setCustomJump(false)
                    .setPrivacyDialogListener(new PrivacyDialogConfig.PrivacyDialogListener() {
                        @Override
                        public void cancel() {
                            finish();
                        }

                        @Override
                        public void confirm() {
                            //一旦用户同意了协议之后 就要初始化第三方的SDK,这里的逻辑修改了界面之后也要记得加上
                            //这里做一下延迟初始化 防止第一次启动时 广告未初始化成功 导致第一次不展示开屏的问题
                            BaseApplication.getApplication().initThirdSdk();
                            goMain();
//                            delayHandler.postDelayed(initDelayRunnable, 1000);
                        }

                        @Override
                        public void clickPrivacyText() {

                        }

                        @Override
                        public void clickAgreementText() {

                        }
                    })
                    .build();
            privacyAgreementDialog.setCancelable(false);
            privacyAgreementDialog.show();
        } else {
            goMain();
        }
    }


    private Runnable initDelayRunnable = new Runnable() {
        @Override
        public void run() {
            applyPermission();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        delayHandler.removeCallbacks(initDelayRunnable);
    }

    /**
     * 申请权限 默认申请读取手机信息 和读写的权限
     */
    private void applyPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (rxPermissions.isGranted(Manifest.permission.READ_PHONE_STATE)) {
                getSwitchKey();
            } else {
                if (checkIsShowApplyPermission()) {
                    dispose = rxPermissions
                            .request(
                                    Manifest.permission.READ_PHONE_STATE
                            ).subscribe(granted -> {
                                //不管用户同不同意权限，都要执行获取开关值,在主页以及功能使用时都要做权限的检测
                                getSwitchKey();
                            });
                    savePermissionApplyTime();
                } else {
                    LogUtils.d("未到下一次权限申请时间------------------>不申请权限");
                    getSwitchKey();
                }
            }
        } else {
            getSwitchKey();
        }
    }

    private void goMain() {
        ARouter.getInstance().build(CommonRoute.COMMON_MAIN).navigation();
        finish();
    }


    @Override
    public void onBackPressed() {
        //启动页不响应返回操作
    }

    private void getSwitchKey() {
        goMain();
    }


    /**
     * 保存本次权限申请时间
     */
    public void savePermissionApplyTime() {
        MmkvUtils.save(KEY_LAST_APPLY_PERMISSION_TIME, System.currentTimeMillis());
    }


    /**
     * 检测本次是否要申请权限,测试环境控制为60s  正式环境为24小时间隔
     *
     * @return
     */
    public boolean checkIsShowApplyPermission() {
        long lastTime = MmkvUtils.get(KEY_LAST_APPLY_PERMISSION_TIME, 0L);
        long currentTime = System.currentTimeMillis();
        long MIN_INTERVAL_TIME = BuildConfig.DEBUG ? 60 * 1000 : 24 * 60 * 60 * 1000;
        LogUtils.d("当前权限间隔多少毫秒：" + (currentTime - lastTime) + " 当前毫秒数："
                + currentTime + " 上次时间：" + lastTime + "最小间隔：" + MIN_INTERVAL_TIME + " 是否申请权限：" + (currentTime - lastTime > MIN_INTERVAL_TIME));
        return (currentTime - lastTime > MIN_INTERVAL_TIME);
    }
}